package edu.guet.server.service;

import edu.guet.server.mapper.*;
import edu.guet.server.model.SemesterStatistic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class StatisticService {
    private static final Logger log = LoggerFactory.getLogger(StatisticService.class);
    @Autowired
    StatisticMapper statisticMapper;
    @Autowired
    SemesterMapper semesterMapper;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private TestMapper testMapper;
    @Autowired
    private StudentHomeworkMapper studentHomeworkMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    CommentMapper commentMapper;

    public ChartCount selectSemCount(Integer semesterId) {
        String start_time = semesterMapper.findStarttimeById(semesterId);
        ChartCount chartCount = new ChartCount();
        chartCount.setStartTime(start_time);
        chartCount.setSemesterId(semesterId);
        chartCount.getLabels().add(start_time);
        chartCount.getData().add(0);
        List<Map<String, Object>> temp = statisticMapper.selectSemCount(chartCount);
        System.out.println(temp);
        for (Map<String, Object> map : temp) {
            // 遍历Map中的每个键值对
            chartCount.getLabels().add(map.get("start_date").toString());
            chartCount.getData().add(map.get("data_count"));
        }
        return chartCount;
    }

    /**
     * 视频观看人数
     *
     * @param semesterId
     * @return
     */
    public ChartCount findVideoCount(Integer semesterId) {
        ChartCount chartCount = new ChartCount();
        chartCount.setSemesterId(semesterId);
        List<Integer> reIds = statisticMapper.findSemResourceIds(semesterId);
        List<Map<String, Object>> temp = statisticMapper.findResoureNameAndCountstu(reIds);
        for (Map<String, Object> map : temp) {
            // 遍历Map中的每个键值对
            chartCount.getLabels().add(map.get("resource_name").toString());
            chartCount.getData().add(map.get("data_count"));
        }
        return chartCount;
    }

    public ChartCount findUnitTestScoreCounts(Integer unitId) throws SQLException {
        ChartCount chartCount = new ChartCount();
//        for (int i = 0; i < 10; i++) {
//            int down = i * 10;
//            int up = (1 + i) * 10;
//            chartCount.getLabels().add(down + "~" + up);
//            //防止100算不上，左闭右开
//            if (up == 100) up += 1;
//            chartCount.getData().add(statisticMapper.findUnitTestScoreCount(unitId, down, up));
//        }
        List<ScoreCount> list = statisticMapper.findUnitTestScoreCount(unitId);
        list.stream()
                .forEach(scoreCount -> {
                    chartCount.addData(scoreCount.getLabels(), scoreCount.getData());
                });
        return chartCount;
    }

    public ChartCount findUnitHmkScoreCounts(Integer unitId) {
        ChartCount chartCount = new ChartCount();
        List<ScoreCount> list = statisticMapper.findUnitHmkScoreCounts(unitId);
        list.stream()
                .forEach(scoreCount -> {
                    chartCount.addData(scoreCount.getLabels(), scoreCount.getData());
                });
        return chartCount;
    }

    @Transactional
    public void UpdateValidScore(SemesterPermissions semesterPermissions) {
        Integer semesterId = semesterPermissions.getSemesterId();
        Double hmkPermission = semesterPermissions.getHmkPermission() / 100.0;
        Double testPermission = semesterPermissions.getTestPermission() / 100.0;
        semesterMapper.addPermissions(hmkPermission, testPermission,semesterId);
        List<Integer> unitIds = unitMapper.findSemUnitIds(semesterId);
        List<Integer> stuIds = semesterMapper.findSemStuIds(semesterId);
        //算每一个同学的单元测试平均分和作业平均分
        for (Integer stuId : stuIds) {
            //计算测试平均分（每个人
            Double ave_stu_test = testMapper.getAverageTestPerUser(stuId, unitIds);
            //计算作业平均分（每个人
            Double ave_stu_hmk = studentHomeworkMapper.getAverageHmkPerUser(stuId, unitIds);
            log.info("测试平均分：{}，作业平均分：{}", ave_stu_test, ave_stu_hmk);
            //填入表格
            if (ave_stu_test != null && ave_stu_hmk != null && stuId != null) {
                semesterMapper.updateAverPerUser(ave_stu_test, ave_stu_hmk, stuId);
                //顺便算每个人的有效成绩
                Double vailScore = testPermission * ave_stu_test + hmkPermission * ave_stu_hmk;
                vailScore = Math.round(vailScore * 100) / 100.0;
                log.info("有效成绩：{}", vailScore);
                semesterMapper.updateSemesterByVaild(stuId, vailScore);
            }
//            //算该课程的测试平均分和作业平均分
//            Double ave_sem_test=semesterMapper.getAverageTest(semesterId);
//            Double ave_sem_hmk=semesterMapper.getAverageHmk(semesterId);
//            //最后写到semester表里
//            if (ave_sem_test != null && ave_sem_hmk != null) {
//                Double vailScore=testPermission*ave_sem_test+hmkPermission*ave_sem_hmk;
//                semesterMapper.updateSemesterByvaildScore(vailScore,semesterId);
//            }
        }
    }

    public ChartCount getValidScores(Integer semesterId) {
//        ChartCount chartCount = new ChartCount();
//        for (int i = 0; i < 10; i++) {
//            int down = i * 10;
//            int up = (1 + i) * 10;
//            chartCount.getLabels().add(down + "~" + up);
//            //防止100算不上，左闭右开
//            if (up == 100) up += 1;
//            chartCount.getData().add(statisticMapper.findValidScoreCounts(semesterId, down, up));
//        }
//        return chartCount;
        ChartCount chartCount = new ChartCount();
        List<ScoreCount> list = statisticMapper.findValidScoreCountsList(semesterId);
        list.stream()
                .forEach(scoreCount -> {
                    chartCount.addData(scoreCount.getLabels(), scoreCount.getData());
                });
        return chartCount;
    }

    public ChartCount getPassValidScores(Integer semesterId) {
        ChartCount chartCount = new ChartCount();
        chartCount.getLabels().add(0 + "~" + 60);
        chartCount.getLabels().add(60 + "~" + 100);
        chartCount.getData().add(statisticMapper.findValidScoreCounts(semesterId, 0, 60));
        chartCount.getData().add(statisticMapper.findValidScoreCounts(semesterId, 60, 101));
        return chartCount;
    }

    public ValidScore getALLValidScore(Integer semesterId) {
        Double max = statisticMapper.getMaxValid(semesterId);
        Double aver = statisticMapper.getAveValid(semesterId);
        Integer cnt = statisticMapper.getStuCount(semesterId);
//        double roundedScore = Math.round(vailScore * 100.0) / 100.0;
        ValidScore validScore = new ValidScore(max, Math.round(aver * 100.0) / 100.0, cnt);
        return validScore;
    }

    public List<Student> getlearningData(Integer semesterId) {
        List<Student> studentList = null;
//        List<Student> studentList = new ArrayList<>();
        List<Integer> stuIds = semesterMapper.findSemStuIds(semesterId);
//        for (Integer stuId : stuIds) {
//            Student student = semesterMapper.getStuAndValid(stuId);
//            if(student==null) continue;
//            Integer videocnt=resourceMapper.getStuVideoCount(stuId,semesterId);
//            String videoDur=resourceMapper.getWatchTime(stuId,semesterId);
//            Integer commentCount=commentMapper.getUserCount(stuId);
//
//            student.setVideoWatchCount(videocnt);
//            student.setVideoWatchDuration(videoDur);
//            student.setDiscussionComments(commentCount);
//            studentList.add(student);
//        }
        studentList = statisticMapper.getStudentData(stuIds, semesterId);
        return studentList;
    }

    public List<Discussion> getDiscussionData(Integer semesterId) {
        List<Integer> stuIds = semesterMapper.findSemStuIds(semesterId);
        log.info("这里是stuids" + stuIds);
        List<Discussion> list = statisticMapper.getDiscussionData(stuIds);
        return list;
    }
}
